package com.lyf.filter;

import cn.hutool.json.JSONObject;
import com.lyf.result.Code;
import com.lyf.result.Result;
import com.lyf.utils.CrossRegion;
import redis.clients.jedis.Jedis;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebFilter("*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //设置编码格式
        servletRequest.setCharacterEncoding("utf-8");
        servletResponse.setCharacterEncoding("utf-8");
        //解决跨域
        CrossRegion.setCross((HttpServletResponse) servletResponse);
        HttpServletRequest hpreq = (HttpServletRequest) servletRequest;
        String servletPath = hpreq.getServletPath();
        System.out.println("请求路径："+servletPath);
        //判断是否是登陆、注册动作
        if(servletPath.equals("/login")){
            //放行
            filterChain.doFilter(servletRequest,servletResponse);
        }else if (servletPath.equals("/register")){
            //放行
            filterChain.doFilter(servletRequest,servletResponse);
        }else if (servletPath.equals("/upload")){
            //放行
            filterChain.doFilter(servletRequest,servletResponse);
        }else if (servletPath.equals("/getCode")){
            //放行
            filterChain.doFilter(servletRequest,servletResponse);
        }
        else if (servletPath.equals("/user/findPassword")){
            //放行
            filterChain.doFilter(servletRequest,servletResponse);
        }
        else if (servletPath.equals("/user/updatePasswordByFind")){
            //放行
            filterChain.doFilter(servletRequest,servletResponse);
        }
        else {
            //到redis获取用户信息
            Jedis jedis = new Jedis("127.0.0.1",6379);
            jedis.auth("123456");
            String id = jedis.get("id");//只是做判断
            //判断是否已经登陆
            if(!id.equals("") && !id.isEmpty()){
                //已经登陆放行
                filterChain.doFilter(servletRequest,servletResponse);
            }else{
                //未登录不放行
                Map<String,Object> map = new HashMap<>();
                Result result = new Result(Code.Fail,null,"你尚未登陆，请先登陆！");
                JSONObject jo = new JSONObject();
                map.put("result",result);
                jo.putAll(map);
                servletResponse.getWriter().println(jo.toString());//响应到浏览器
            }
        }
    }

    @Override
    public void destroy() {

    }
}
